<template>
  <!--数据脱敏-->
  <div class="container">
    <a-divider orientation="left" orientation-margin="0px">工具箱脱敏任务</a-divider>
    <a-row class="toolbox-left">
      <a-col :span="24" v-if="toolboxcom">
        <a-form :model="formState" name="validate_other" v-bind="formItemLayout" @finish-failed="onFinishFailed" @finish="onFinish" :rules="formRules">
          <a-form-item>
            <a-form-item name="dragger" noStyle>
              <a-upload-dragger
                v-model:fileList="fileList"
                name="file"
                :multiple="false"
                :action="originalAction"
                :beforeUpload="beforeUpload"
                :data="(file) => ({ fileName: file.name, fileSize: file.size })"
                :headers="uploadHeaders"
                @change="handleChange"
                @drop="handleDrop"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
                <p class="ant-upload-hint" style="padding: 10px 14px 0">支持对以下文件类型的数据进行脱敏处理：DMP、TXT、CSV、XLSX、XLS、DEL、DCM、E 及包含这些格式的 ZIP/TAR/TAR.GZ 压缩包。</p>
              </a-upload-dragger>
            </a-form-item>
          </a-form-item>
          <a-divider orientation="left" orientation-margin="0px">选择脱敏规则</a-divider>
          <a-form-item name="group">
            <a-cascader v-model:value="formState.datadesensitization" :options="options" :placeholder="placeholder" size="large" />
          </a-form-item>
          <a-form-item style="text-align: center">
            <a-button type="primary" htmlType="submit" size="large" :disabled="isSubmitting">开始脱敏</a-button>
          </a-form-item>
        </a-form>
      </a-col>

      <a-col :span="24" class="toolboxbut" v-if="toolboxbut">
        <!--正在处理文件-->
        <a-space v-if="loading" class="loading">
          <a-spin tip="文件正在处理中..." size="large" />
        </a-space>

        <!--开始下载-->

        <a-result status="success" title="文件脱敏成功" :subTitle="subTitle" v-if="dowbut">
          <template #extra>
            <a-button type="primary" size="large" @click="postDownload">
              <template #icon>
                <DownloadOutlined />
              </template>
              下载文件
            </a-button>
          </template>
        </a-result>
      </a-col>

      <a-col :span="24" class="toolboxend" v-if="toolboxend">
        <a-button size="large" @click="goToToolbox">返回工具箱</a-button>
      </a-col>
    </a-row>

    <a-row>
      <a-col :span="24" class="zi_bottom">
        <p>工具对上传的文件进行敏感数据识别和脱敏处理，保障文件供给安全，使用步骤如下：​</p>
        <p>（1）上传文件​</p>
        <p>（2）点击【脱敏规则】选择合适脱敏规则​</p>
        <p>（3）点击【开始脱敏】显示脱敏效果，确认效果后点击【提交脱敏】​</p>
        <p>（4）处理完成后，点击【下载】将已脱敏的文件下载至本地​​</p>
        <p>（5）若脱敏规则不适用，可联系平台管理员调整。​</p>
      </a-col>
    </a-row>
  </div>
</template>
<script lang="ts" setup>
import type { UploadChangeParam, UploadFile } from 'ant-design-vue'
import type { DesensitizationItem } from '@/types'
import type { ApiResult } from '@/types/app'
import { reactive } from 'vue'
import { dmsMaskCenterApi } from '@/api/dms-mask-center'
import { GetDownloadList } from '@/api/dms-mask-center/type'
import { IframeEventTypeEnum } from '@/enums/appEnum'
import { useIframeMessenger } from '@/hooks/useIframeMessenger'
import { useUserStoreWithOut } from '@/stores/modules/user'
import { http } from '@/utils/http'
import { UploadOutlined, InboxOutlined, DownloadOutlined, BookFilled } from '@ant-design/icons-vue'
import { message, CascaderProps } from 'ant-design-vue'
import { useRoute } from 'vue-router'
const { postToParent } = useIframeMessenger({ allowOrigin: '*', debug: true })
const fileList = ref<UploadFile[]>([])
const subTitle = ref('')
const namekey = ref('')
const wataskid = ref('')
const loading = ref(false)
const dowbut = ref(false)
const isSubmitting = ref(false)
const absPath = ref('')
const toolboxcom = ref(true)
const toolboxbut = ref(false)
const toolboxend = ref(false)
const formRules = {}
const route = useRoute()
const handleChange = (info: UploadChangeParam) => {
  const status = info.file.status
  if (status === 'done') {
    message.success('文件上传成功！')
    const response = info.file.response
    subTitle.value = info.file.name
    // console.log('后端返回内容：', response);
    namekey.value = response.data.key
    absPath.value = response.data.absPath
  } else if (status === 'error') {
    message.error(`文件上传失败！`)
  }
}
const beforeUpload = (file: UploadFile) => {
  // 检查当前文件列表长度，若已有文件则阻止上传
  if (fileList.value.length >= 1) {
    message.warning('只能上传一个文件，请先删除已上传的文件！')
    return false // 阻止上传
  }
  return true
}
function handleDrop(e: DragEvent) {
  console.log(e)
}

//请求头内容
const uploadHeaders = {
  Authorization: `Bearer ${useUserStoreWithOut().getToken()}` // 示例：添加身份令牌
}
const formState = reactive<Record<string, any>>({})

//脱敏策略数据
const options = ref<CascaderProps['options']>([])
const placeholder = ref<string>('请选择脱敏规则')
const datadesensitization = ref('')
// 组件挂载时获取数据
// 组件挂载时获取数据
onMounted(async () => {
  const taskId = route.query.taskId as string; // 从 URL  query 中获取 taskId
  handleTaskId(taskId);

  try {
    // 调用接口获取数据
    const response = await dmsMaskCenterApi.getDesensitization()
    const rawData: DesensitizationItem[] = response.data // 假设数据在 response.data 中

    if (rawData && rawData.length > 0) {
      // 1. 映射数据为级联选择器需要的格式（value + label）
      options.value = rawData.map((item) => ({
        value: item.id,
        label: item.name,
        // 处理子级（如果有）
        children: item.children?.map((child) => ({
          value: child.id,
          label: child.name
        }))
      }))

      // 2. 将第一个数据的 label 设为默认占位符
      placeholder.value = options.value[0].label
      formState.datadesensitization = [options.value[0].value]
    } else {
      // 没有数据时显示默认提示
      placeholder.value = '暂无脱敏规则数据'
    }
  } catch (error) {
    message.error('获取数据失败，请重试')
  }
})
const originalAction = import.meta.env.VITE_GLOB_API_URL + 'dms-mask-center/api/v1/resource/uploadOssFile'

const value = ref<string[]>([])
//提交执行
const onFinish = (values: any) => {
  if (fileList.value.length <= 0) {
    message.error('请上传需要脱敏的文件！');
    return false
  } else if (!formState.datadesensitization) {
    message.error('请选择脱敏数据类型！');
    return false
  }
  //按钮禁用
  isSubmitting.value = true
  // 获取各时间部分并补零
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，需+1
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const formattedTime = `${year}${month}${day}${hours}${minutes}`
  dmsMaskCenterApi
    .postWatermark({
      data: {
        name: '工具箱脱敏任务' + formattedTime,
        type: 'DATA_MASK',
        mode: 'FILE_TO_FILE',
        classifyIds: formState.datadesensitization,
        sourceResourceId: import.meta.env.VITE_GLOB_SRID,
        cycleType: 'IMMEDIATE',
        watermarkRuleId: '1',
        ticketNumber: formattedTime,
        provideDataParty: '1',
        useDataParty: '1',
        noResSourceWaterMarkFileFlag: false,
        noResTargetWaterMarkFileFlag: false,
        sourceFilePathSelect: [
          {
            absPath: absPath.value
          }
        ],
        fileSelect: [
          {
            fileNameKey: namekey.value,
            fileName: subTitle.value,
            absPath: absPath.value
          }
        ],
        fileEncoding: 'UTF-8',
        autoMaskFlag: 'NO',
        dataType: 'offline'
      }
    })
    .then((response) => {
      dowbut.value = false;
      loading.value = true;

      toolboxbut.value = true;
      toolboxend.value = true;
      // console.log(response.data.id);
      // http.put<ApiResult<any>>({ url: '/dms-mask-center/api/v1/task/submit/' + response.data.id })
      wataskid.value = response.data.id;
      // 通知父窗口
      postToParent({ type: IframeEventTypeEnum.Desensitization, data: response.data })
    })
    .catch((error) => {
      // message.warning('提交失败！');
      isSubmitting.value = false;
    })

  console.log('Success:', values)
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
}
//下载文件
const postDownload = async (record: any) => {
  dmsMaskCenterApi.getDownloadList()
    .then((response) => {
      const dataList = response.data || [];
      const matchedItem = dataList.find((item) => item.taskId === wataskid.value);
      window.open('https://' + window.location.host + '/dms-mask-center/api/v1/dataoffline/task/downloadRecord/watermark-file?id=' + matchedItem.id + '&taskId=' + wataskid.value);
      fileList.value = [];
    })
    .catch((error) => {
      message.warning('文件脱敏失败请重新尝试！')
      console.log('1111');
    })
}
//提交加水印
const postwatermark = () => {}

// 新增：处理 taskId 的核心函数
const handleTaskId = async (taskId: string | undefined) => {
  if (taskId) {
    // 初始化状态：禁用按钮 + 显示加载
    toolboxcom.value = false;
    loading.value = true;
    toolboxbut.value = true;
    toolboxend.value = true;
    isSubmitting.value = true;
    wataskid.value = taskId;

    // 定义定时器变量
    let checkInterval: NodeJS.Timeout;
    
    // 循环请求接口的函数
    const checkStatus = () => {
      dmsMaskCenterApi
        .getDownloadList()
        .then((response) => {
          const dataList = response.data || [];

          const normalizedTaskId = String(taskId).trim();
          // 筛选时同样处理每一项的 taskId
          const matchedItem = dataList.find((item) => {
            // 将 item.taskId 转为字符串并去除首尾空格，再比较
            return String(item.taskId).trim() === normalizedTaskId;
          });
          
          console.log('当前查询结果:', matchedItem);
          
          // 找到匹配的taskId时处理
          if (matchedItem) {
            // 清除定时器，停止循环请求
            clearInterval(checkInterval);
            
            // 回显文件信息
            subTitle.value = matchedItem.fileName;
            const fileObj: UploadFile = {
              uid: '1',
              name: matchedItem.fileName || '未知文件名',
              status: 'done',
              response: '上传成功'
            };
            fileList.value = [fileObj];
            
            // 结束加载状态
            loading.value = false;
            dowbut.value = true;
            isSubmitting.value = false;
          }
          // 未匹配到时继续循环请求（定时器会继续执行）
        })
        .catch((error) => {
          console.error('查询失败:', error);
          message.warning('查询状态失败，请稍后重试');
          // 发生错误时停止循环，避免无限报错
          clearInterval(checkInterval);
          loading.value = false;
          isSubmitting.value = false;
        });
    };
    
    // 立即执行一次请求，然后每隔3秒执行一次（可根据需求调整间隔时间）
    checkStatus();
    checkInterval = setInterval(checkStatus, 2000);
  }
};

const router = useRouter()
const goToToolbox = () => {
  // 使用 router.push 跳转到指定路由
  // location.href='./data/#/toolbox-desensitization';
  toolboxcom.value = true;
  toolboxbut.value = false;
  isSubmitting.value = false;
  toolboxend.value = false;
}
</script>

<style scoped>
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
.form-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}
.ant-form-item .ant-form-item-label > label {
  font-size: 16px;
}
:where(.css-dev-only-do-not-override-10npqub).ant-upload-wrapper .ant-upload-drag p.ant-upload-drag-icon .anticon {
  font-size: 7rem;
}
:where(.css-dev-only-do-not-override-10npqub).ant-upload-wrapper .ant-upload-drag p.ant-upload-text {
  color: #1890ff;
}
.container .zi_bottom {
  border-top: solid 10px #eef4ff;
  padding: 1rem 0;
}
.ant-result .ant-result-title {
  color: #1890ff;
  font-size: 18px;
}
.ant-result {
  padding-top: 11vh;
}
.container .toolboxbut {
  border: 1px dashed #d9d9d9;
  text-align: center;
  min-height: 42vh;
}
.container .toolboxbut .loading {
  padding-top: 20vh;
}
.container .toolboxend {
  text-align: center;
  margin: 28px 0;
}
.ant-result .ant-result-extra {
  margin-top: 12px;
}
.zi_bottom h1 {
  font-size: 16px;
}
.zi_bottom p {
  color: #999;
}
</style>
